<template>
	<div class="box" style="padding: 10px;">
		<div style="height: 89vh; overflow-y: auto;padding: 10px 0; box-sizing: border-box;">
			<view class="functions-area" v-for="(item,index) in list" :key="index">
				<view class="function-card">
					<view class="card-header">
						<!-- 左侧标题区域 -->
						<view class="header-title">
							<view class="card-icon study-icon"></view>
							<text class="card-title">{{item.className}}</text>
						</view>

						<div>
							<!-- 右侧添加按钮 -->
							<button class="card-add-btn" @click="addChildren(item)">
								<text>添加</text>
							</button>
							
							<button class="card-add-btn" style="background-color: #F8BD12;" @click="editClass(item)">
								<text>修改</text>
							</button>
							
							<button class="card-add-btn" style="background-color: #FF1234;" @click="delClass(item)">
								<text>删除</text>
							</button>
						</div>
					</view>

					<view class="card-content">
						<view class="function-grid">
							<view class="function-item" v-for="(row,inx) in item.children" :key="inx">
								<image :src="row.iconUrl" />
								<text>{{row.menuName}}</text>
								<van-icon @click="editMenu(row)" name="edit" class="editIcon" />
								<van-icon @click="delMenu(row)" name="cross" class="delIcon" />
							</view>
							<view class="empty" v-if="item.children.length == 0">
								快去添加菜单吧~
							</view>
						</view>
					</view>
				</view>
			</view>
			</view>
		</div>

		<button class="add-category-btn" @click="addClass">
			<text>添加分类</text>
		</button>

		<!-- 添加分类 -->
		<van-popup :show="isShowAmusing" @close="isShowAmusing = false" position="top" custom-style="height: 30%;">
			<view class="popup-wrapper">
				<van-field :value="addClassForm.className" type="textarea" label="分类名称" placeholder="请输入分类名称" :border="true"
					class="share-input" @change="(e) => (addClassForm.className = e.detail)" />
				<van-field type="textarea" label="所属位置" :border="true" class="share-input">
					<van-radio-group :value="addClassForm.location" @change="(e) => (addClassForm.location = e.detail)" slot="input">
						<div style="display: flex;align-items: center;margin-bottom: 10px;">
							<van-radio name="ggx">工具箱</van-radio>
							<van-radio name="wd" style="margin-left: 10px;">我的</van-radio>
						</div>
					</van-radio-group>
				</van-field>
				<button class="submit-btn" @click="addSave">添加分类</button>
			</view>
		</van-popup>

		<!-- 添加/修改子集 -->
		<van-popup :show="isChildrenShow" @close="handleChildrenPopupClose" position="top" custom-style="height: 45%;">
			<view class="popup-wrapper">
				<van-field :value="addForm.className" label="父级名称" disabled @change="(e) => (className = e.detail)" />
				<div class="upload">
					<div class="uploadTitle">菜单图标</div>
					<van-uploader :file-list="fileList" max-count="1" @delete="deleteImages" @after-read="afterRead"
						slot="button" />
				</div>

				<van-field :value="addForm.menuName" label="菜单名称" placeholder="请输入菜单名称"
					@change="(e) => (addForm.menuName = e.detail)" />

				<van-field :value="addForm.pathUrl" label="跳转地址" placeholder="请输入跳转地址"
					@change="(e) => (addForm.pathUrl = e.detail)" />

				<button class="submit-btn" @click="addChildrenSave">
					<text>{{ addForm._id ? '更新菜单' : '确定' }}</text>
				</button>
			</view>
		</van-popup>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				isShowAmusing: false,
				isChildrenShow: false,
				addForm: {},
				addClassForm:{
					className: "",
					location:'ggx'
				},
				list: [],
				fileList: [],
				// 保存原始图标用于修改时恢复
				originalIconUrl: ''
			}
		},

		onLoad() {
			this.getInit()
		},

		methods: {
			addClass() {
				this.addClassForm =  {
					location:'ggx',
					className:''
				}
				this.isShowAmusing = true
			},
			
			// 修改分类
			editClass(item){
				this.addClassForm =  {...item}
				this.isShowAmusing = true
			},
			
			// 删除分类
			delClass(item){
				uni.showModal({
					title: "提示",
					content: "确定要删除这个菜单分类吗？",
					success: async (res) => {
						if (res.confirm) {
							let result = await this.$axios('overallSituation', {
								databaseName:'menu',
								state:'delete',
								_id:item._id
							})
							if(result.code == 200){
								this.$showToast("删除成功")
								this.getInit()
							}
						}
					},
				});
			},

			// 获取菜单
			async getInit() {
				let result = await this.$axios('menuManage', {}, true)
				if (result.code == 200) {
					this.list = result.data || []
					this.list.forEach(item => {
						if (!Array.isArray(item.children)) item.children = []
					})
				}
			},

			async addSave() {
				if (!this.addClassForm.className) {
					this.$showToast('请输入分类名称')
					return
				}
				
				let parmse = {
					state: this.addClassForm._id ? "update" : "add",
					...this.addClassForm,
					createTime: this.addClassForm.createTime || this.$getTime(),
					databaseName: 'menu'
				}
				await this.$axios('overallSituation', parmse)
				this.isShowAmusing = false
				this.getInit()
			},

			// 添加子菜单
			addChildren(item) {
				this.addForm = {
					className: item.className,
					classId: item._id
				}
				this.fileList = []
				this.originalIconUrl = ''
				this.isChildrenShow = true
			},
			
			// 修改子菜单
			editMenu(row) {
				// 深拷贝要修改的菜单数据
				this.addForm = {...row}
				// 保存原始图标URL
				this.originalIconUrl = row.iconUrl
				// 如果有图标，显示在上传区域
				this.fileList = row.iconUrl ? [{
					url: row.iconUrl,
					suffix: this.$getFileExtensionName(row.iconUrl)
				}] : []
				this.isChildrenShow = true
			},

			async addChildrenSave() {
				if (!this.addForm.menuName) {
					this.$showToast('请填写菜单名称')
					return
				}
				
				if (!this.addForm.pathUrl) {
					this.$showToast('请输入跳转地址')
					return
				}

				if (this.fileList.length == 0 && !this.addForm._id) {
					this.$showToast('请上传菜单图标')
					return
				}

				let parmse = {
					...this.addForm,
					createTime: this.$getTime(),
					databaseName: 'menuDetail',
					state: this.addForm._id ? 'update' : 'add'
				}

				// 如果是修改且未更换图片，则使用原始图片URL
				if (!this.addForm._id || (this.fileList.length > 0 && this.fileList[0].url !== this.originalIconUrl)) {
					let imageRes = await uniCloud.uploadFile({
						filePath: this.fileList[0].url,
						cloudPath: "菜单图标" + this.fileList[0].suffix,
						header: {
							"Content-Type": "multipart/form-data",
						},
					});

					parmse.iconUrl = imageRes.fileID
				}

				let result = await this.$axios('overallSituation', parmse)
				if (result.code == 200) {
					this.getInit()
					this.isChildrenShow = false
				}
			},

			// 删除子菜单
			async delMenu(item) {
				uni.showModal({
					title: "提示",
					content: "确定要删除这个菜单吗？",
					success: async (res) => {
						if (res.confirm) {
							let parmse = {
								...item,
								state: "delete",
								databaseName: 'menuDetail',
							};
							let res = await this.$axios("overallSituation", parmse)
							if (res.code == 200) {
								this.getInit();
								uni.showToast({
									title: "删除成功",
									icon: "success",
									duration: 2000,
								});
							}
						}
					},
				});
			},

			// 关闭子菜单弹窗时重置表单
			handleChildrenPopupClose() {
				this.isChildrenShow = false;
				this.addForm = {};
				this.fileList = [];
				this.originalIconUrl = '';
			},

			// 删除图片回调函数
			deleteImages(e) {
				this.fileList.splice(e.detail.index, 1);
			},

			// 文件上传
			afterRead(e) {
				let suffix = this.$getFileExtensionName(e.detail.file.url)
				if (suffix != '.svg') {
					this.$showToast("请上传svg格式的图片")
					return
				}
				// 清空现有列表，确保只保留一张图片
				this.fileList = [{
					url: e.detail.file.url,
					suffix: suffix
				}];
			},
		}
	}
</script>

<style scoped>
	.functions-area {
		display: flex;
		flex-direction: column;
		gap: 20px;
		margin-bottom: 24px;
	}

	.function-card {
		background-color: #fff;
		border-radius: 12px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
		overflow: hidden;
	}

	/* 卡片头部布局 - 实现两端对齐 */
	.card-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 16px 20px;
		width: 100%;
		box-sizing: border-box;
		border-bottom: 1px solid #f5f5f5;
	}

	/* 左侧标题区域 */
	.header-title {
		display: flex;
		align-items: center;
	}

	.card-icon {
		width: 24px;
		height: 24px;
		border-radius: 6px;
		margin-right: 12px;
	}

	/* 主题色相关样式 */
	.study-icon {
		background-color: rgba(59, 130, 246, 0.1);
		/* 学习类主题色 - 淡蓝 */
	}

	.life-icon {
		background-color: rgba(16, 185, 129, 0.1);
		/* 生活类主题色 - 淡绿 */
	}

	.entertainment-icon {
		background-color: rgba(139, 92, 246, 0.1);
		/* 娱乐类主题色 - 淡紫 */
	}

	.work-icon {
		background-color: rgba(245, 158, 11, 0.1);
		/* 工作类主题色 - 淡黄 */
	}

	.card-title {
		font-size: 16px;
		font-weight: 600;
		color: #1F2937;
	}

	.card-content {
		padding: 16px;
	}

	.function-grid {
		display: flex;
		flex-wrap: wrap;
		gap: 10px;
	}

	.function-item {
		width: calc(25% - 7.5px);
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 15px 10px;
		box-sizing: border-box;
		background-color: #f9fafb;
		border-radius: 8px;
		transition: all 0.2s ease;
		position: relative;
	}

	.function-item:active {
		background-color: #f0f4f8;
		transform: scale(0.96);
	}

	.function-item image {
		width: 36px;
		height: 36px;
		margin-bottom: 8px;
	}

	.function-item text {
		font-size: 12px;
		color: #4B5563;
		text-align: center;
		line-height: 1.3;
	}

	/* 按钮样式优化 - 与主题色搭配 */
	.add-category-btn,
	.card-add-btn {
		border: none;
		border-radius: 8px;
		font-size: 14px;
		font-weight: 500;
		cursor: pointer;
		transition: all 0.2s ease;
		display: inline-flex;
		align-items: center;
		justify-content: center;
	}

	/* 顶部添加分类按钮 - 使用主题色 */
	.add-category-btn {
		background-color: #3B82F6;
		/* 学习类主色 - 蓝色 */
		color: white;
		padding: 10px 16px;
		margin-bottom: 16px;
		box-sizing: border-box;
		width: 100%;
		height: 40px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	/* 卡片内添加按钮 - 使用对应分类的主题色 */
	.card-add-btn {
		background-color: #4fb9ff;
		/* 与学习类图标同色系 */
		padding: 6px 14px;
		box-sizing: border-box;
		height: 30px;
		margin-left: 5px;
		color: #fff;
	}

	/* 交互效果 */
	.add-category-btn:hover,
	.card-add-btn:hover {
		opacity: 0.92;
	}

	.add-category-btn:active,
	.card-add-btn:active {
		transform: scale(0.97);
	}

	.popup-wrapper {
		position: relative;
		width: 100%;
		height: 100%;
	}

	.share-input {
		width: 100%;
		height: 40px;
		padding: 10px;
		box-sizing: border-box;
		color: #333;
	}

	.submit-btn {
		position: absolute;
		bottom: 10px;
		left: 50%;
		width: 95%;
		transform: translateX(-50%);
		height: 40px;
		background-color: #4fb9ff;
		color: #fff;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 14px;
		font-weight: 500;
	}

	.empty {
		width: 100%;
		height: 50px;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 14px;
		font-weight: 500;
		color: #4fb9ff;
	}

	.delIcon {
		position: absolute;
		top: 4px;
		right: 4px;
		color: #FF1234;
	}

	.editIcon {
		position: absolute;
		top: 4px;
		left: 4px;
		color: #F8BD12;
	}

	/* 悬停效果增强 */
	.delIcon:hover, .editIcon:hover {
		transform: scale(1.1);
		transition: transform 0.2s ease;
	}

	.upload {
		display: flex;
		align-items: center;
		padding: 10px 0;
		box-sizing: border-box;
	}

	.uploadTitle {
		color: #646566;
		font-size: 14px;
		box-sizing: border-box;
		width: 86.8px;
		margin-right: 12px;
		margin-left: 16px;
	}
</style>